package com.ssy.lingxi.member.merchant.serviceimpl.mobile;

import com.ssy.lingxi.common.constant.manage.ShopPropertyEnum;
import com.ssy.lingxi.common.constant.manage.ShopTypeEnum;
import com.ssy.lingxi.common.constant.member.MemberLevelTypeEnum;
import com.ssy.lingxi.common.constant.member.MemberStatusEnum;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.constant.MemberRelationTypeEnum;
import com.ssy.lingxi.member.merchant.api.constant.MemberRightAcquireWayEnum;
import com.ssy.lingxi.member.merchant.api.constant.MemberRightParamWayEnum;
import com.ssy.lingxi.member.merchant.api.constant.MemberRightTypeEnum;
import com.ssy.lingxi.member.merchant.config.ServiceConfig;
import com.ssy.lingxi.member.merchant.entity.*;
import com.ssy.lingxi.member.merchant.model.bo.LevelBO;
import com.ssy.lingxi.member.merchant.model.constant.MemberDetailVersionEnum;
import com.ssy.lingxi.member.merchant.model.constant.MemberOuterStatusEnum;
import com.ssy.lingxi.member.merchant.model.constant.MemberUserAuthTypeEnum;
import com.ssy.lingxi.member.merchant.model.constant.MemberValidateStatusEnum;
import com.ssy.lingxi.member.merchant.model.vo.basic.request.MobileUserPageVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.request.UpdateRegisterDetailVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.request.UpperMemberIdRoleIdVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.RegisterDetailGroupVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.UserQueryVO;
import com.ssy.lingxi.member.merchant.model.vo.info.response.*;
import com.ssy.lingxi.member.merchant.model.vo.lifecycle.response.MemberCreditComplaintPageQueryVO;
import com.ssy.lingxi.member.merchant.model.vo.maintenance.request.MemberDetailCreditHistoryPageVO;
import com.ssy.lingxi.member.merchant.model.vo.maintenance.response.*;
import com.ssy.lingxi.member.merchant.model.vo.mobile.request.*;
import com.ssy.lingxi.member.merchant.model.vo.mobile.response.MobileInfoApplyButtonVO;
import com.ssy.lingxi.member.merchant.model.vo.mobile.response.MobileUpdateDepositDetailQueryVO;
import com.ssy.lingxi.member.merchant.model.vo.mobile.response.MobileValidateHistoryVO;
import com.ssy.lingxi.member.merchant.model.vo.validate.request.ValidateIdPageVO;
import com.ssy.lingxi.member.merchant.model.vo.validate.request.ValidateIdVO;
import com.ssy.lingxi.member.merchant.model.vo.validate.response.ValidateStepVO;
import com.ssy.lingxi.member.merchant.model.vo.validate.response.WorkFlowStepVO;
import com.ssy.lingxi.member.merchant.repository.MemberRelationRepository;
import com.ssy.lingxi.member.merchant.repository.MemberRepository;
import com.ssy.lingxi.member.merchant.repository.MemberValidateHistoryRepository;
import com.ssy.lingxi.member.merchant.service.base.*;
import com.ssy.lingxi.member.merchant.service.mobile.IMobileMemberInfoService;
import com.ssy.lingxi.member.merchant.utils.NumberUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * App - 会员信息管理查询服务接口实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2020-12-08
 */
@Service
public class MobileMemberInfoServiceImpl implements IMobileMemberInfoService {
    @Resource
    private IBaseMemberCacheService memberCacheService;

    @Resource
    private IBaseMemberRegisterDetailService baseMemberRegisterDetailService;

    @Resource
    private IBaseMemberShopService baseMemberShopService;

    @Resource
    private IBaseMemberDetailService baseMemberDetailService;

    @Resource
    private IBaseMemberInfoService baseMemberInfoService;

    @Resource
    private IBaseMemberInnerService baseMemberInnerService;

    @Resource
    private MemberRepository memberRepository;

    @Resource
    private MemberRelationRepository relationRepository;

    @Resource
    private MemberValidateHistoryRepository memberValidateHistoryRepository;

    @Resource
    private IBaseUserDetailService baseUserDetailService;

    @Resource
    private IBaseMemberLevelConfigService baseMemberLevelConfigService;

    @Resource
    private IBaseSiteService siteService;

    /**
     * “会员中心“ - 根据前端商城类型、属性，查询会员关系
     *
     * @param loginUser     登录用户
     * @param shopType      商城类型
     * @param shopProperty  商城属性
     * @param upperMemberId 上级会员Id
     * @param upperRoleId   上级角色Id
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberRelationDO> findMobileMemberRelation(UserLoginCacheDTO loginUser, Integer shopType, Integer shopProperty, Long upperMemberId, Long upperRoleId) {
        MemberRelationDO relationDO;
        if(shopType.equals(ShopTypeEnum.ENTERPRISE.getCode()) && (shopProperty.equals(ShopPropertyEnum.UNION_B.getCode()) || shopProperty.equals(ShopPropertyEnum.UNION_C.getCode()))) {
            relationDO = relationRepository.findFirstBySubMemberIdAndSubRoleIdAndRelType(loginUser.getMemberId(), loginUser.getMemberRoleId(), MemberRelationTypeEnum.PLATFORM.getCode());
            if (relationDO == null || !relationDO.getSubMemberId().equals(loginUser.getMemberId()) || !relationDO.getSubRoleId().equals(loginUser.getMemberRoleId())) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
            }
        } else if(shopType.equals(ShopTypeEnum.ENTERPRISE.getCode()) && (shopProperty.equals(ShopPropertyEnum.SELF_B.getCode()) || shopProperty.equals(ShopPropertyEnum.SELF_C.getCode()))) {
            if(!loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.MERCHANT.getCode())) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_LEVEL_TYPE_NOT_MATCHED);
            }

            if(NumberUtil.isNullOrZero(upperMemberId) || NumberUtil.isNullOrZero(upperRoleId)) {
                return Wrapper.fail(ResponseCode.MC_MS_SELF_SHOP_UPPER_MEMBER_CAN_NOT_BE_EMPTY);
            }

            relationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(upperMemberId, upperRoleId, loginUser.getMemberId(), loginUser.getMemberRoleId());

            if (relationDO != null && (!relationDO.getSubMemberId().equals(loginUser.getMemberId()) || !relationDO.getSubRoleId().equals(loginUser.getMemberRoleId()))) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
            }

        } else if(shopType.equals(ShopTypeEnum.CHANNEL.getCode()) || shopType.equals(ShopTypeEnum.CHANNEL_SELF.getCode())) {
            if(!loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.CHANNEL.getCode())) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_LEVEL_TYPE_NOT_MATCHED);
            }

            relationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(upperMemberId, upperRoleId, loginUser.getMemberId(), loginUser.getMemberRoleId());

            if (relationDO != null && (!relationDO.getSubMemberId().equals(loginUser.getMemberId()) || !relationDO.getSubRoleId().equals(loginUser.getMemberRoleId()))) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
            }
        } else {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_SHOP_MISMATCHED);
        }

        return Wrapper.success(relationDO);
    }

    /**
     * 查找登录会员的logo
     *
     * @param loginUser 登录用户
     * @return 会员Logo
     */
    @Override
    public String findMemberLogo(UserLoginCacheDTO loginUser) {
        if(loginUser.getUserType().equals(MemberUserAuthTypeEnum.ADMIN.getCode())) {
            return loginUser.getLogo();
        }

        MemberDO member = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        return member == null ? "" : member.getLogo();
    }

    /**
     * “我的-卡包” - 分页查询归属会员列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileInfoLevelRightQueryVO>> pageUpperMemberLevelRights(HttpHeaders headers, PageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        Pageable pageable = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findBySubMemberIdAndSubRoleIdAndRelTypeAndVerified(loginUser.getMemberId(), loginUser.getMemberRoleId(), MemberRelationTypeEnum.OTHER.getCode(), MemberValidateStatusEnum.VERIFY_PASSED.getCode(), pageable);

        //前端展示的是“店铺名称”
        Map<Long, Long> memberMap = pageList.getContent().stream().collect(Collectors.toMap(MemberRelationDO::getMemberId, MemberRelationDO::getRoleId));
        List<MemberShopDO> memberShops = baseMemberShopService.findMemberShops(memberMap);

        //注意！！！这里返回的是下级会员（即当前登录会员）的memberId，所以都是一样的
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MobileInfoLevelRightQueryVO infoVO = new MobileInfoLevelRightQueryVO();
            infoVO.setValidateId(relationDO.getId());
            infoVO.setUpperMemberId(relationDO.getMemberId());
            infoVO.setUpperRoleId(relationDO.getRoleId());
            infoVO.setLogo("");
            memberShops.stream().filter(shop -> shop.getMemberId().equals(relationDO.getMemberId()) && shop.getRoleId().equals(relationDO.getRoleId())).findFirst().ifPresent(shop -> {
                infoVO.setUpperMemberName(shop.getName());
                infoVO.setLogo(shop.getLogo());
            });

            if(!StringUtils.hasLength(infoVO.getUpperMemberName())) {
                infoVO.setUpperMemberName(relationDO.getMember().getName());
            }

            infoVO.setLevel(relationDO.getLevelRight().getLevel());
            infoVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            infoVO.setScore(relationDO.getLevelRight().getScore());
            LevelBO levelBO = baseMemberLevelConfigService.findNextLevel(relationDO.getMemberId(), relationDO.getRoleId(),relationDO.getSubRoleId(), relationDO.getLevelRight().getLevel());
            infoVO.setNextLevelTag(levelBO.getNextTag());
            infoVO.setNextScore(levelBO.getNextScore());
            infoVO.setSumReturnMoney(relationDO.getLevelRight().getSumReturnMoney());
            infoVO.setCurrentPoint(relationDO.getLevelRight().getCurrentPoint());
            infoVO.setStatus(relationDO.getStatus());
            infoVO.setStatusName(MemberStatusEnum.getCodeMessage(infoVO.getStatus()));

            return infoVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “会员中心” - 查询当前会员的积分、权益信息
     * @param headers    Http头部信息
     * @param shopVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MobileInfoLevelRightVO> getMemberDetailLevelRight(HttpHeaders headers, MobileShopVO shopVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        //如当前商城类型是企业商城且商城属性为B端商城或C端商城时，查询当前会员角色归属至平台的会员等级、会员权益、信用信息；
        //如当前商城类型是企业商城且商城属性为B端自营商城或C端自营商城时，查询当前会员角色归属至当前自营商城所属的商户会员的会员等级、会员权益、信用信息；
        //如当前商城类型是渠道商城或渠道自有商城时，查询归属于渠道商城首页选择的上级渠道的会员权益
        Wrapper<MemberRelationDO> relationResult = findMobileMemberRelation(loginUser, shopVO.getShopType(), shopVO.getShopProperty(), shopVO.getUpperMemberId(), shopVO.getUpperRoleId());
        if(relationResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(relationResult.getCode(), relationResult.getMessage());
        }

        MemberRelationDO relationDO = relationResult.getData();
        if(relationDO == null) {
            return Wrapper.success(new MobileInfoLevelRightVO(findMemberLogo(loginUser)));
        }

        MemberLevelRightDO levelDO = relationDO.getLevelRight();
        if (levelDO == null) {
            return Wrapper.success(new MobileInfoLevelRightVO(findMemberLogo(loginUser)));
        }

        MobileInfoLevelRightVO levelRightVO = new MobileInfoLevelRightVO();
        levelRightVO.setUpperMemberId(relationDO.getMemberId());
        levelRightVO.setUpperRoleId(relationDO.getRoleId());
        levelRightVO.setLogo(relationDO.getSubMember().getLogo());
        levelRightVO.setLevel(levelDO.getLevel());
        levelRightVO.setLevelTag(levelDO.getLevelTag());
        levelRightVO.setScore(levelDO.getScore());
        levelRightVO.setNextScore(levelDO.getLevelConfig() == null ? 0 : levelDO.getLevelConfig().getPoint());
        levelRightVO.setCurrentPoint(levelDO.getCurrentPoint());
        levelRightVO.setSumReturnMoney(levelDO.getSumReturnMoney());
        LevelBO levelBO = baseMemberLevelConfigService.findNextLevel(relationDO.getMemberId(), relationDO.getRoleId(), relationDO.getSubRoleId(), relationDO.getLevelRight().getLevel());
        //下一等级
        levelRightVO.setNextLevelTag(levelBO.getNextTag());
        //权益列表
        levelRightVO.setRights(new ArrayList<>());

        if(levelDO.getLevelConfig() == null || CollectionUtils.isEmpty(levelDO.getLevelConfig().getRights())) {
            return Wrapper.success(levelRightVO);
        }

        List<MemberDetailRightConfigVO> configVOList = levelDO.getLevelConfig().getRights().stream().map(memberRightConfigDO -> {
            MemberDetailRightConfigVO configVO = new MemberDetailRightConfigVO();
            configVO.setId(memberRightConfigDO.getId());
            configVO.setRightTypeEnum(memberRightConfigDO.getRightType());
            configVO.setName(MemberRightTypeEnum.getCodeMsg(memberRightConfigDO.getRightType()));
            configVO.setRemark(MemberRightTypeEnum.getRemark(memberRightConfigDO.getRightType()));
            configVO.setAcquireWay(MemberRightAcquireWayEnum.getCodeMsg(memberRightConfigDO.getAcquireWay()));
            configVO.setParamWay(MemberRightParamWayEnum.getCodeMsg(memberRightConfigDO.getParamWay()));
            configVO.setStatus(memberRightConfigDO.getStatus());
            String param = String.format("%.2f", memberRightConfigDO.getParameter().multiply(new BigDecimal(100)).doubleValue()).concat("%");
            configVO.setParameter(param);
            return configVO;
        }).collect(Collectors.toList());

        levelRightVO.setRights(configVOList);

        return Wrapper.success(levelRightVO);
    }

    /**
     * “会员中心”  - 分页查询权益获取记录
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDetailRightHistoryVO>> pageMemberDetailRightHistory(HttpHeaders headers, MobileShopPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        Wrapper<MemberRelationDO> relationResult = findMobileMemberRelation(loginUser, pageVO.getShopType(), pageVO.getShopProperty(), pageVO.getUpperMemberId(), pageVO.getUpperRoleId());
        if(relationResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(relationResult.getCode(), relationResult.getMessage());
        }

        if(relationResult.getData() == null) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        return baseMemberDetailService.pageMemberDetailRightHistory(relationResult.getData(), pageVO.getCurrent(), pageVO.getPageSize(), ServiceConfig.APP_DEFAULT_DATETIME_FORMATTER);
    }

    /**
     * “会员中心”  - 分页查询权益获取记录
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDetailRightSpendHistoryVO>> pageMemberDetailRightSpendHistory(HttpHeaders headers, MobileShopPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        Wrapper<MemberRelationDO> relationResult = findMobileMemberRelation(loginUser, pageVO.getShopType(), pageVO.getShopProperty(), pageVO.getUpperMemberId(), pageVO.getUpperRoleId());
        if(relationResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(relationResult.getCode(), relationResult.getMessage());
        }

        if(relationResult.getData() == null) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        return baseMemberDetailService.pageMemberDetailRightSpendHistory(relationResult.getData(), pageVO.getCurrent(), pageVO.getPageSize(), ServiceConfig.APP_DEFAULT_DATETIME_FORMATTER);
    }

    /**
     * “会员中心” - 分页查询等级分获取记录
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDetailLevelHistoryVO>> pageMemberLevelDetailHistory(HttpHeaders headers, MobileShopPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);

        Wrapper<MemberRelationDO> relationResult = findMobileMemberRelation(loginUser, pageVO.getShopType(), pageVO.getShopProperty(), pageVO.getUpperMemberId(), pageVO.getUpperRoleId());
        if(relationResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(relationResult.getCode(), relationResult.getMessage());
        }

        if(relationResult.getData() == null) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        return baseMemberInfoService.pageMemberLevelDetailHistory(relationResult.getData(), pageVO.getCurrent(), pageVO.getPageSize(), ServiceConfig.APP_DEFAULT_DATETIME_FORMATTER);
    }

    /**
     * 会员详情 - 会员基本信息
     *
     * @param headers    Http头部信息
     * @param shopVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MobileInfoBasicDetailVO> getMemberBasicDetail(HttpHeaders headers, MobileShopVO shopVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        Wrapper<MemberRelationDO> relationResult = findMobileMemberRelation(loginUser, shopVO.getShopType(), shopVO.getShopProperty(), shopVO.getUpperMemberId(), shopVO.getUpperRoleId());
        if(relationResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(relationResult.getCode(), relationResult.getMessage());
        }

        //如果没有上下级关系，查询平台会员
        MemberRelationDO relationDO = relationResult.getData();
        if(relationDO == null) {
            relationDO = relationRepository.findFirstBySubMemberIdAndSubRoleIdAndRelType(loginUser.getMemberId(), loginUser.getMemberRoleId(), MemberRelationTypeEnum.PLATFORM.getCode());
            if(relationDO == null) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
            }
        }

        return baseMemberInfoService.getMobileMemberBasicDetail(relationDO);
    }

    /**
     * 分页查询归属会员列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<UpperMemberInfoVO>> pageUpperMembers(HttpHeaders headers, PageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        Wrapper<Boolean> wrapper = siteService.isEnableMultiTenancy(headers);
        // TODO: 2022/3/14    不确定是否要对【会员等级类型】为【平台会员】的会员数据 进行筛选
        return baseMemberInfoService.pageUpperMembers(loginUser.getMemberId(), loginUser.getMemberRoleId(), "", "", "", null, pageVO.getCurrent(), pageVO.getPageSize(), wrapper.getData());
    }

    /**
     * 会员详情 - 诚信信息 - 会员基本信用信息
     *
     * @param headers    Http头部信息
     * @param idVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberDetailCreditVO> getMemberDetailCredit(HttpHeaders headers, ValidateIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return baseMemberInfoService.getMemberDetailCredit(loginUser, idVO.getValidateId());
    }

    /**
     * 会员详情 - 会员信用信息 - 交易评价汇总
     *
     * @param headers    Http头部信息
     * @param idVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MobileCommentSummaryVO> getMemberDetailCreditTradeCommentSummary(HttpHeaders headers, ValidateIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return baseMemberInfoService.getMobileMemberDetailTradeCommentSummary(loginUser, idVO.getValidateId());
    }

    /**
     * 会员详情 - 会员信用 - 分页查询交易评论历史记录
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDetailCreditTradeHistoryVO>> pageMemberDetailCreditTradeCommentHistory(HttpHeaders headers, MemberDetailCreditHistoryPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return baseMemberInfoService.pageMemberDetailCreditTradeCommentHistory(loginUser, pageVO);
    }

    /**
     * 会员详情 - 会员信用信息 - 售后评价汇总
     *
     * @param headers    Http头部信息
     * @param idVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MobileCommentSummaryVO> getMemberDetailCreditAfterSaleCommentSummary(HttpHeaders headers, ValidateIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return baseMemberInfoService.getMobileMemberDetailCreditAfterSaleCommentSummary(loginUser, idVO.getValidateId());
    }

    /**
     * 会员详情 - 会员信用 - 分页查询售后评论历史记录
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDetailCreditAfterSaleHistoryVO>> pageMemberDetailCreditAfterSaleCommentHistory(HttpHeaders headers, MemberDetailCreditHistoryPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return baseMemberInfoService.pageMemberDetailCreditAfterSaleCommentHistory(loginUser, pageVO);
    }

    /**
     * 会员详情 - 会员信用 - 投诉汇总
     *
     * @param headers    Http头部信息
     * @param idVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberDetailCreditComplainSummaryVO> getMemberDetailCreditComplainSummary(HttpHeaders headers, ValidateIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return baseMemberInfoService.getMemberDetailCreditComplainSummary(loginUser, idVO.getValidateId());
    }

    /**
     * 会员详情 - 会员信用 - 分页查询投诉历史记录
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberCreditComplaintPageQueryVO>> pageMemberDetailCreditComplainHistory(HttpHeaders headers, ValidateIdPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return baseMemberInfoService.pageMemberDetailCreditComplainHistory(loginUser, pageVO);
    }

    /**
     * 查询审批流程
     * @param headers    Http头部信息
     * @param idVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<ValidateStepVO> getMobileOuterValidateSteps(HttpHeaders headers, ValidateIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        MemberRelationDO relationDO = relationRepository.findById(idVO.getValidateId()).orElse(null);
        if (relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        ValidateStepVO stepVO = new ValidateStepVO();
        if(relationDO.getVerified().equals(MemberValidateStatusEnum.VERIFY_PASSED.getCode())) {
            stepVO.setCurrentStep(2);
        } else {
            stepVO.setCurrentStep(1);
        }

        List<WorkFlowStepVO> stepList = new ArrayList<>();
        WorkFlowStepVO workFlowStepVO = new WorkFlowStepVO();
        workFlowStepVO.setStep(1);
        workFlowStepVO.setStepName("申请会员");
        workFlowStepVO.setRoleName(relationDO.getSubRole().getRoleName());
        stepList.add(workFlowStepVO);

        workFlowStepVO = new WorkFlowStepVO();
        workFlowStepVO.setStep(2);
        workFlowStepVO.setStepName("审核会员");
        workFlowStepVO.setRoleName(relationDO.getRole().getRoleName());
        stepList.add(workFlowStepVO);

        stepVO.setSteps(stepList);

        return Wrapper.success(stepVO);
    }

    /**
     * 分页查询审核历史记录
     * @param headers    Http头部信息
     * @param pageVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MobileValidateHistoryVO>> pageMobileMemberOuterValidateHistory(HttpHeaders headers, ValidateIdPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        MemberRelationDO relationDO = relationRepository.findById(pageVO.getValidateId()).orElse(null);
        if (relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        Pageable page = PageRequest.of(pageVO.getCurrent() -1, pageVO.getPageSize(), Sort.by("createTime").descending());
        Page<MemberValidateHistoryDO> pageList = memberValidateHistoryRepository.findByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(relationDO.getMemberId(), relationDO.getRoleId(), relationDO.getSubMemberId(), relationDO.getSubRoleId(), page);

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(h -> {
            MobileValidateHistoryVO historyVO = new MobileValidateHistoryVO();
            historyVO.setCreateTime(h.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
            historyVO.setName(h.getMemberName());
            historyVO.setOperation(h.getOperation());
            historyVO.setRoleName(h.getRoleName());
            historyVO.setStatus(h.getOuterStatus());
            historyVO.setStatusDescription(MemberOuterStatusEnum.getCodeMsg(h.getOuterStatus()));
            historyVO.setRemark(h.getRemark());
            return historyVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 获取“修改会员信息”页面，会员注册资料信息
     *
     * @param headers    Http头部信息
     * @return 查询结果
     */
    @Override
    public Wrapper<List<RegisterDetailGroupVO>> getMemberRegisterDetail(HttpHeaders headers) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        MemberDO member = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if(member == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        return Wrapper.success(baseMemberRegisterDetailService.groupMemberRegisterDetail(member, MemberDetailVersionEnum.USING));
    }

    /**
     * 修改会员信息
     *
     * @param headers  Http头部信息
     * @param detailVO 接口参数
     * @return 修改结果
     */
    @Override
    public Wrapper<Void> updateMemberRegisterDetail(HttpHeaders headers, UpdateRegisterDetailVO detailVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);

        //修改注册信息后，强制重新提交平台审核
        //由于注册信息是所有角色共用的，所以要判断所有角色的平台会员
        List<MemberRelationDO> relationList = relationRepository.findBySubMemberIdAndRelType(loginUser.getMemberId(), MemberRelationTypeEnum.PLATFORM.getCode());
        if(CollectionUtils.isEmpty(relationList)) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        MemberRelationDO relationDO = relationList.stream().filter(relation -> relation.getSubMemberId().equals(loginUser.getMemberId()) && relation.getSubRoleId().equals(loginUser.getMemberRoleId())).findFirst().orElse(null);
        if (relationDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //审核进行中（状态不为“通过”、“未通过”），不能修改信息
        MemberRelationDO otherRoleRelation = relationList.stream().filter(relation -> !relation.getOuterStatus().equals(MemberOuterStatusEnum.PLATFORM_VERIFY_PASSED.getCode()) && !relation.getOuterStatus().equals(MemberOuterStatusEnum.PLATFORM_VERIFY_NOT_PASSED.getCode())).findFirst().orElse(null);
        if(otherRoleRelation != null) {
            return Wrapper.fail(otherRoleRelation.getId().equals(relationDO.getId()) ? ResponseCode.MC_MS_MEMBER_VERIFYING : ResponseCode.MC_MS_MEMBER_HAS_ANOTHER_ROLE_IS_VERIFYING);
        }

        return baseMemberRegisterDetailService.updatePlatformMemberRegisterDetail(relationDO, "", detailVO.getDetail(), false,true);
    }

    /**
     * 分页查询会员下属用户
     * @param headers Http头部新
     * @param pageVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<UserQueryVO>> pageUsers(HttpHeaders headers, MobileUserPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return baseUserDetailService.pageUsers(loginUser.getMemberId(), pageVO.getKeyword(), pageVO.getCurrent(), pageVO.getPageSize(), true);
    }

    /**
     * “店铺会员”页面，查询“申请会员”按钮状态和文本
     *
     * @param headers     Http头部信息
     * @param upperMemberVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MobileInfoApplyButtonVO> getMobileApplyCondition(HttpHeaders headers, UpperMemberIdRoleIdVO upperMemberVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return baseMemberInfoService.getMobileApplyCondition(loginUser, upperMemberVO.getUpperMemberId(), upperMemberVO.getUpperRoleId());
    }

    /**
     * “店铺会员”页面，查询“入会享特权”的权益列表
     *
     * @param headers       Http头部信息
     * @param upperMemberVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<MemberDetailRightConfigVO>> getUpperMemberRights(HttpHeaders headers, UpperMemberIdRoleIdVO upperMemberVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return Wrapper.success(baseMemberLevelConfigService.findSubMemberRights(upperMemberVO.getUpperMemberId(), upperMemberVO.getUpperRoleId(), loginUser.getMemberRoleId()));
    }

    /**
     * “店铺会员”页面，申请成为会员时，查询需要填写的入库资料
     *
     * @param headers       Http头部信息
     * @param upperMemberVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<RegisterDetailGroupVO>> findMobileApplyDepositDetails(HttpHeaders headers, UpperMemberIdRoleIdVO upperMemberVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        Wrapper<MemberInfoApplyDepositDetailVO> depositDetailResult = baseMemberInfoService.getApplyDepositDetail(loginUser, upperMemberVO.getUpperMemberId(), upperMemberVO.getUpperRoleId());
        if(depositDetailResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(depositDetailResult.getCode(), depositDetailResult.getMessage());
        }

        return Wrapper.success(depositDetailResult.getData().getDepositDetails());
    }

    /**
     * “店铺会员”页面，修改入库资料时，查询已有的入库资料信息
     *
     * @param headers       Http头部信息
     * @param upperMemberVO 接口参数
     * @return 修改结果
     */
    @Override
    public Wrapper<MobileUpdateDepositDetailQueryVO> getMemberDepositDetail(HttpHeaders headers, @Valid UpperMemberIdRoleIdVO upperMemberVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return baseMemberInfoService.getMemberDepositDetail(loginUser, upperMemberVO.getUpperMemberId(), upperMemberVO.getUpperRoleId());
    }

    /**
     * “店铺会员”页面，当审核不通过时，修改入库资料
     *
     * @param headers         Http头部信息
     * @param depositDetailVO 接口参数
     * @return 修改结果
     */
    @Override
    public Wrapper<Void> updateDepositDetail(HttpHeaders headers, MobileUpdateDepositDetailVO depositDetailVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return baseMemberInfoService.updateMobileDepositDetail(loginUser, depositDetailVO);
    }

    /**
     * “申请会员” - 提交
     *
     * @param headers Http头部信息
     * @param subVO   接口参数
     * @return 申请结果
     */
    @Override
    public Wrapper<Void> applyToBeSubMember(HttpHeaders headers, MobileApplyForSubVO subVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        return baseMemberInnerService.applyToBeSubMember(subVO.getUpperMemberId(), subVO.getUpperRoleId(), loginUser.getMemberId(), loginUser.getMemberRoleId(), subVO.getDepositDetails(), subVO.getQualities());
    }

    /**
     * “店铺会员” - 查询当前会员的等级、权益信息
     *
     * @param headers               Http头部信息
     * @param upperMemberIdRoleIdVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MobileInfoLevelRightVO> getShopMemberDetailLevelRight(HttpHeaders headers, UpperMemberIdRoleIdVO upperMemberIdRoleIdVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);
        MemberRelationDO relationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(upperMemberIdRoleIdVO.getUpperMemberId(), upperMemberIdRoleIdVO.getUpperRoleId(), loginUser.getMemberId(), loginUser.getMemberRoleId());
        if(relationDO == null) {
            return Wrapper.success(new MobileInfoLevelRightVO(findMemberLogo(loginUser)));
        }

        MemberLevelRightDO levelDO = relationDO.getLevelRight();
        if (levelDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_LEVEL_DOES_NOT_EXIST);
        }

        MobileInfoLevelRightVO levelRightVO = new MobileInfoLevelRightVO();
        levelRightVO.setUpperMemberId(relationDO.getMemberId());
        levelRightVO.setUpperRoleId(relationDO.getRoleId());
        levelRightVO.setLogo(relationDO.getSubMember().getLogo());
        levelRightVO.setLevel(levelDO.getLevel());
        levelRightVO.setLevelTag(levelDO.getLevelTag());
        levelRightVO.setScore(levelDO.getScore());
        levelRightVO.setNextScore(levelDO.getLevelConfig() == null ? 0 : levelDO.getLevelConfig().getPoint());
        levelRightVO.setCurrentPoint(levelDO.getCurrentPoint());
        levelRightVO.setSumReturnMoney(levelDO.getSumReturnMoney());
        LevelBO levelBO = baseMemberLevelConfigService.findNextLevel(relationDO.getMemberId(), relationDO.getRoleId(), relationDO.getSubRoleId(), relationDO.getLevelRight().getLevel());
        //下一等级
        levelRightVO.setNextLevelTag(levelBO.getNextTag());
        //权益列表
        levelRightVO.setRights(new ArrayList<>());

        if(levelDO.getLevelConfig() == null || CollectionUtils.isEmpty(levelDO.getLevelConfig().getRights())) {
            return Wrapper.success(levelRightVO);
        }

        List<MemberDetailRightConfigVO> configVOList = levelDO.getLevelConfig().getRights().stream().map(memberRightConfigDO -> {
            MemberDetailRightConfigVO configVO = new MemberDetailRightConfigVO();
            configVO.setId(memberRightConfigDO.getId());
            configVO.setRightTypeEnum(memberRightConfigDO.getRightType());
            configVO.setName(MemberRightTypeEnum.getCodeMsg(memberRightConfigDO.getRightType()));
            configVO.setRemark(MemberRightTypeEnum.getRemark(memberRightConfigDO.getRightType()));
            configVO.setAcquireWay(MemberRightAcquireWayEnum.getCodeMsg(memberRightConfigDO.getAcquireWay()));
            configVO.setParamWay(MemberRightParamWayEnum.getCodeMsg(memberRightConfigDO.getParamWay()));
            configVO.setStatus(memberRightConfigDO.getStatus());
            String param = String.format("%.2f", memberRightConfigDO.getParameter().multiply(new BigDecimal(100)).doubleValue()).concat("%");
            configVO.setParameter(param);
            return configVO;
        }).collect(Collectors.toList());

        levelRightVO.setRights(configVOList);

        return Wrapper.success(levelRightVO);
    }

    /**
     * “店铺会员”  - 分页查询会员权益获取记录
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDetailRightHistoryVO>> pageShopMemberDetailRightHistory(HttpHeaders headers, MobileUpperPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);

        MemberRelationDO relationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(pageVO.getUpperMemberId(), pageVO.getUpperRoleId(), loginUser.getMemberId(), loginUser.getMemberRoleId());
        if(relationDO == null) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        return baseMemberDetailService.pageMemberDetailRightHistory(relationDO, pageVO.getCurrent(), pageVO.getPageSize(), ServiceConfig.APP_DEFAULT_DATETIME_FORMATTER);
    }

    /**
     * “店铺会员”  - 分页查询会员权益使用记录
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDetailRightSpendHistoryVO>> pageShopMemberDetailRightSpendHistory(HttpHeaders headers, MobileUpperPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);

        MemberRelationDO relationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(pageVO.getUpperMemberId(), pageVO.getUpperRoleId(), loginUser.getMemberId(), loginUser.getMemberRoleId());
        if(relationDO == null) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        return baseMemberDetailService.pageMemberDetailRightSpendHistory(relationDO, pageVO.getCurrent(), pageVO.getPageSize(), ServiceConfig.APP_DEFAULT_DATETIME_FORMATTER);
    }

    /**
     * “店铺会员”  - 分页查询活跃分获取记录
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDetailLevelHistoryVO>> pageShopMemberLevelDetailHistory(HttpHeaders headers, MobileUpperPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromMobile(headers);

        MemberRelationDO relationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(pageVO.getUpperMemberId(), pageVO.getUpperRoleId(), loginUser.getMemberId(), loginUser.getMemberRoleId());
        if(relationDO == null) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        return baseMemberDetailService.pageMemberLevelDetailHistory(relationDO, pageVO.getCurrent(), pageVO.getPageSize(), ServiceConfig.APP_DEFAULT_DATETIME_FORMATTER);
    }
}
